#include <HTTP/server/my_server.h>

WebServer ESP32_Server(80);

void Server_Init(){
  ESP32_Server.on("/",PAGE_Root);
  ESP32_Server.on("/connect",PAGE_ConnectWiFi);
  //ESP32_Server.on("/generate_204",PAGE_Root);
  ESP32_Server.on("/api/wifi/networks.json",HTTP_GET,API_ReturnNetworks);
  ESP32_Server.on("/api/wifi/connect",HTTP_POST,API_ConnectNetwork);
  ESP32_Server.onNotFound(PAGE_Root);
  ESP32_Server.begin();
  Serial.println("server client start");
  Serial.println();

}

void CilentServer()
{
  ESP32_Server.handleClient();
}

void PAGE_Root()
{
  if(WiFi.status()==WL_CONNECTED)
  {
    ESP32_Server.sendHeader("meta","charset=UTF-8",true);
    ESP32_Server.send(200,"text/html",readFile("/html/main.html"));    
  }
  else
  {
    //ESP32_Server.sendHeader("meta","charset=UTF-8",true);
    ESP32_Server.send(302,"text/html","<meta http-equiv=\"refresh\" content=\"0; url=/connect\" />");
    //delay(200); 
    //ESP32_Server.client().stop();
    Serial.println("重定向至连接页");
  }

}

void PAGE_ConnectWiFi()
{
  if(WiFi.status()==WL_CONNECTED)
  {  
    //ESP32_Server.sendHeader("meta","charset=UTF-8",true);
    ESP32_Server.send(302,"text/html","<meta http-equiv=\"refresh\" content=\"0; url=/\" />");
    Serial.println("重定向代码<meta http-equiv=\"refresh\" content=\"0; url=/\" />");
  }
  else
  {

    //ESP32_Server.sendHeader("meta","charset=UTF-8",true);
    ESP32_Server.send(200,"text/html",readFile("/html/connect.html"));  

  }
}

void API_ConnectNetwork()
{
  JsonDocument ConnectInfo,ResponseInfo;
  JsonDocument* saved_aps=Wifi_GetSavedAps();
  String s_ResponseInfo;
  uint8_t ConnectStatus;
  if(ESP32_Server.method()==HTTP_POST)
  {
    Serial.println("received:"+ESP32_Server.arg(0));
    deserializeJson(ConnectInfo,ESP32_Server.arg(0));
  
    /*连接WiFi并检查连接状态*/
    if((ConnectStatus=ConnectWiFi(ConnectInfo["ssid"],ConnectInfo["password"]))==WL_CONNECTED)
    {
      ResponseInfo["success"]=true;
      ResponseInfo["newIP"]=WiFi.localIP().toString();
      ResponseInfo["message"]="连接成功";

      Serial.println("connected");
      Serial.println("server ip:"+WiFi.localIP().toString());
    }
    else if(ConnectStatus==WL_DISCONNECTED)
    {
      ResponseInfo["success"]=false;
      ResponseInfo["newIP"]="0.0.0.0";
      ResponseInfo["message"]="请检查密码是否正确";
      Serial.println("connection failed");
    }
    else
    {
      ResponseInfo["success"]=false;
      ResponseInfo["newIP"]="0.0.0.0";
      ResponseInfo["message"]="连接失败";
      Serial.println("connection failed");

    }
    serializeJson(ResponseInfo,s_ResponseInfo);

    /*wifi连接后，关闭AP并获取NTP时间*/
    ESP32_Server.sendHeader("meta","charset=UTF-8",true);
    ESP32_Server.send_P(200,"text/json",s_ResponseInfo.c_str());
    if(ConnectStatus==WL_CONNECTED)
    {
      setClock();
      WiFi.softAPdisconnect();
      String s_ap;
      bool isSameSSID=false;
      for(JsonObject ap : (*saved_aps)["ap"].as<JsonArray>())
      {
        if(ap["ssid"]==ConnectInfo["ssid"])
        {
          ap["password"]=ConnectInfo["password"];
          isSameSSID=true;
          break;
        }
      }
      if(isSameSSID==false)
      {
        JsonObject ap;

        ap=(*saved_aps)["ap"].add<JsonObject>();
        ap["ssid"]=ConnectInfo["ssid"];
        ap["password"]=ConnectInfo["password"];
      }
      serializeJson((*saved_aps),s_ap);
      writeFile("/saved_aps/networks.json",s_ap);
      
    }
  }
}

void API_ReturnNetworks()
{
  JsonDocument networks;
  JsonArray ap;
  JsonObject j_ssid;

  String s_networks,ssid;
  int32_t rssi,channel;
  uint8_t enctype;
  uint8_t *bssid;

  networks["status"]=-2;
  ap=networks["ap"].to<JsonArray>();
  if(ESP32_Server.method()==HTTP_GET)
  {
    if(WiFi.status()==WL_CONNECTED)
    {
      ESP32_Server.sendHeader("meta","charset=UTF-8",true);
      ESP32_Server.send(301,"text/html","<meta http-equiv=\"refresh\" content=\"0; url=\" />");  
    }
    else
    {
      Serial.println("Scaning APs");
      networks["status"]=WiFi.scanNetworks();
      if(networks["status"]==-1)
      {
        Serial.println("Scaning APs code:-1");//正在扫描热点
      }
      else if(networks["status"]>=0)
      {
        //热点扫描完成
        Serial.println("Scaning Compete!");

        for (size_t i = 0; i < networks["status"]; i++)
        {
          WiFi.getNetworkInfo(i,ssid,enctype,rssi,bssid,channel);
  
          j_ssid=ap.add<JsonObject>();
          j_ssid["ssid"]=ssid;
          j_ssid["signal"]=rssi;
          j_ssid["enc_type"]=enctype;        
        }  
      }
      else
      {
        //错误情况
      }

      //发送json文件
      serializeJson(networks,s_networks);
      ESP32_Server.sendHeader("meta","charset=UTF-8",true);
      ESP32_Server.send(200,"text/json",s_networks);  
    }
  }
}
